# encoding:utf-8
from flask import render_template, session, current_app, g, abort, jsonify, request

from Info import db
from Info.models import User, News, Comment, CommentLike
from Info.module.news import news_blu
from Info.utils.common import user_longin_data
from Info.utils.response_code import RET

@news_blu.route('comment_like',methods = ['POST'])
@user_longin_data
def comment_like():
    """
    一、前端
    1、当我点赞的时候，手变蓝色，赞变成1
    2、如果用户没有登录，需要弹出登录框
    3、当我们取消点赞，变为原有状态
    二、后端
     1、需要user 和 comment_id  action
     2、ajax. post


    :return:
    """
    user = g.user
    if not user:
        return  jsonify(errno = RET.SESSIONERR,errmsg = '用户未登陆')
    params_data=request.json
    comment_id = params_data.get('comment_id')
    action = params_data.get('action')
    if not all([comment_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    if action not in ['add','remove']:
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg= '参数错误')
    try:
        comment_obj = Comment.query.get(comment_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据库查询错误')
    if not comment_obj:
        return jsonify(errno = RET.NODATA,errmsg = '评论不存在')
    # 核心业务逻辑：记录点赞状态
    # 查询该条赞是否存在
    comment_like_obj = CommentLike.query.filter(CommentLike.user_id==user.id,
                                         CommentLike.comment_id ==comment_obj.id).first()
    if action =='add':
        if not comment_like_obj:
    # 如果我已经点了赞了
            comment_like=CommentLike()
            comment_like.comment_id = comment_obj.id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment_obj.like_count +=1
    else:
        if comment_like_obj:
            db.session.delete(comment_like_obj)
            comment_obj.like_count -=1
    try:
        db.session.commit()
    except Exception as e :
        current_app.logger.error(e)
        db.session.rollbacK()
        return  jsonify(errno = RET.DBERR,errmsg = '数据库保存失败')
    return  jsonify(errno = RET.OK,errmsg = 'OK')







@news_blu.route('/news_comment',methods = ['POST'])
@user_longin_data
def news_comment():
    """
    新闻评论
     1、接收参数
     2、校验参数
     3、业务逻辑  初始化一个评论对象 添加到数据库
     4、返回响应
    :return:
    """
    user = g.user
    if not user:
        return  jsonify(errno = RET.SESSIONERR,errmsg = '用户未登录')
    params_dict = request.json
    news_id = params_dict.get("news_id")
    comment_content = params_dict.get("comment_content")
    parent_id = params_dict.get("parent_id")
    if not all([news_id,comment_content]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        comment_content.logger.error(e)
        return jsonify(errno=RET.PARAMERR , errmsg = '参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno = RET.DBERR,errmsg = '数据查询失误')
    if not news:
        return  jsonify(errno = RET.NODATA,errmsg = '新闻不存在')
    comment = Comment()
    comment.user_id=user.id
    comment.news_id = news.id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e :
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '数据保存失败')
    return jsonify(errno = RET.OK,errmsg = '评论成功', data=comment.to_dict())


@news_blu.route('/news_collect',methods = ['POST'])
@user_longin_data
def news_collect():
    #  新闻收藏
    # 1、接收参数
    # 2、校验参数
    # 3、查询出该条新闻
    # 4、往用户收藏新闻的列表中添加新闻
    # 5、返回响应
    user = g.user
    if not user:
        return  jsonify(errno = RET.SESSIONERR,errmsg = '用户未登录')
    params_dict = request.json
    news_id = params_dict.get("news_id")
    action = params_dict.get("action")
    if not all([news_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    if action not in ['collect','cancel_collect']:
        return  jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    try:
        news_id =  int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据库查询错误')
    if not news:
        return  jsonify(errno = RET.NODATA,errmsg = '该新闻不存在')
    if action =='collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    return jsonify(errno = RET.OK,errmsg = 'OK')

@news_blu.route('/<int:news_id>')
@user_longin_data
def detail(news_id):

    user = g.user
    news_list =  News.query.order_by(News.clicks.desc()).limit(6).all()
    news_dict_li = []
    for news_obj in news_list:
        news_dict_li.append(news_obj.to_basic_dict())

    news =  None
    try:
        news = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
        abort(500)
    if not news:
        abort(404)
    news.clicks += 1
    is_collected =  False
    if user:
        if news in user.collection_news:
            is_collected=True

    comment_list = Comment.query.filter(Comment.news_id==news.id).order_by(Comment.create_time.desc()).all()
    # comment_dict_li =[comment.to_dict() for comment in comment_list]
    comment_like_ids = []
    if user :
    # 1、获取所有评论的id  []
        comment_ids = [comment.id for comment in comment_list]
        comment_like_objs = CommentLike.query.filter(CommentLike.user_id == user.id,CommentLike.comment_id.in_(comment_ids)).all()
        comment_like_ids = [comment_like.comment_id for comment_like in comment_like_objs]
    comment_dict_li = []
    for comment_obj in comment_list:
        comment_dict = comment_obj.to_dict()
        comment_dict["is_like"] = False
        if comment_obj.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)
    # print(comment_dict_li)
    data = {
        'user_info':user.to_dict()if user else None,
        'news_dict_li':news_dict_li,
        'news':news.to_dict(),
        'is_collected':is_collected,
        'comments':comment_dict_li
    }
    # print(comment_like_ids)

    return render_template('news/detail.html',data=data)